package com.jci.xyf.hellofx.taobao;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.jci.xyf.hellofx.mysqlconn;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class Controller2 {
    @FXML
    private Label taobaos;
    @FXML
    private TextField tbTxt;
    @FXML
    protected void taobaoselect() {
        //起到一个Loading的效果
        taobaos.setText("Loading……");
        String taobaoVal = tbTxt.getText();
        mysqlconn my = new mysqlconn();
        my.startmysql();
        //异步机制
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                String url = "https://qqlykm.cn/api/tb/api.php?so=" + taobaoVal;
                String result = HttpUtil.get(url);
                result = result.substring(5, result.length() - 4);
                taobao tbs = JSONUtil.toBean(result, taobao.class);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String sqlexit = "SELECT *\n" + "FROM tbinf\n" + "WHERE name='" + taobaoVal + "';";
                ResultSet rs = my.query(sqlexit);
                try {
                    if(rs.next()==false){
                        String out="商品有："+"\n";
                        for(List<String> list:tbs.getResult()){
                            for(int i=0;i<2;i++){
                                if(i==0){
                                    out+="商品名称："+list.get(i)+"\t";
                                }else{
                                    out+="店铺ID"+list.get(i)+"\n";
                                }
                            }
                        }
                        taobaos.setText(out);
                        for(List<String> list: tbs.getResult()){
                            String sql1="INSERT\n" + "INTO tbinf\n" + "VALUES('"+taobaoVal+"','"+list.get(0)+"','"+list.get(1)+"');";
                            my.updata(sql1);
                        }
                    }else{
                        String out="商品有："+"\n";
                        while(rs.next()){
                            out+="商品名称："+rs.getString("商品名称")+"\t";
                            out+="店铺ID："+rs.getString("店铺ID")+"\n";
                        }
                        taobaos.setText(out);
                    }

                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
